package com.hlju.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlju.reggie.bean.*;
import com.hlju.reggie.common.BaseContext;
import com.hlju.reggie.common.CustException;
import com.hlju.reggie.mapper.OrdersMapper;
import com.hlju.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private CartService cartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddresBookService addresBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    @Transactional
    public void saveOrder(Orders orders) throws CustException {
        //获取当前用户ID
        Long userId = BaseContext.getCurrentId();

        //查询当前用户的购物车数据
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<Cart> cartList = cartService.list(wrapper);

        //如果购物车中没有数据 提示错误信息
        if (cartList == null || cartList.size() == 0) {
            throw new CustException("购物车为空，不能下单！");
        }

        //根据用户id查询用户信息
        User user = userService.getById(userId);

        //根据地址id查询地址信息
        AddressBook addressBook = addresBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustException("用户地址信息有误，不能下单！");
        }

        //生成一个订单号
        long orderNumber = IdWorker.getId();

        //创建订单明细集合
        List<OrderDetail> detailList = new ArrayList<>();

        //定义存放总金额的对象
        AtomicInteger amount = new AtomicInteger(0);

        //遍历购物车集合
        for (Cart cart : cartList) {
            OrderDetail detail = new OrderDetail();
            detail.setOrderId(orderNumber);
            detail.setNumber(cart.getNumber());
            detail.setDishFlavor(cart.getDishFlavor());
            detail.setDishId(cart.getDishId());
            detail.setSetmealId(cart.getSetmealId());
            detail.setName(cart.getName());
            detail.setImage(cart.getImage());
            detail.setAmount(cart.getAmount());
            //将明细对象添加到明细集合
            detailList.add(detail);
            //遍历的时候刚好可以累加计算总金额 (当前购物车对象的单价 * 数量的结果累加给 总金额对象amount)
            amount.addAndGet(cart.getAmount().multiply(new BigDecimal(cart.getNumber())).intValue());
        }
        //组装订单数据
        orders.setId(orderNumber);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(1);
        orders.setUserId(userId);
        orders.setNumber(orderNumber + "");
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setAmount(new BigDecimal(amount.get()));
        //向订单表插入数据
        this.save(orders);
        //向明细表批量插入数据
        orderDetailService.saveBatch(detailList);
        //清空当前用户购物车数据
        cartService.remove(wrapper);
    }

    @Override
    public void again(Orders orders) {
        //根据订单id查询订单明细
        QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",orders.getId());
        List<OrderDetail> detailList = orderDetailService.list(wrapper);
        //创建购物车集合
        List<Cart> cartList = new ArrayList<>();
        //遍历明细集合
        for (OrderDetail detail : detailList) {
            //创建购物车对象
            Cart cart = new Cart();
            //属性赋值
            BeanUtils.copyProperties(detail,cart);
            //给购物车对象设置用户ID
            cart.setUserId(BaseContext.getCurrentId());
            //设置创建时间
            cart.setCreateTime(LocalDateTime.now());
            //将购物车对象添加进集合
            cartList.add(cart);
        }
        //给购物车表中批量加入数据
        cartService.saveBatch(cartList);
    }
}
